package com.chat.interceptor;

import com.chat.result.Result;
import com.chat.utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        String token = request.getHeader("token");
//        if (token == null) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            writeErrorResponse(response, 401, "未提供token");
//            log.error("令牌为空null");
//            return false;
//        }
//
//        try {
//            if (JwtUtil.isExpired(token)) {
//                writeErrorResponse(response, 401, "token已过期");
//                log.warn("令牌过期: {}", token);
//                return false;
//            }
//
//            Claims claims = JwtUtil.parseToken(token);
//            log.info("claims = {}", claims);
//
//            if (claims.getSubject().equals("REFRESH_TOKEN")){
//                writeErrorResponse(response,401,"refresh_token 不难直接访问接口");
//                return false;
//            }
//        } catch (Exception e) {
//            writeErrorResponse(response, 401, "token无效");
//            log.error("令牌解析失败: {}", e.getMessage());
//            return false;
//        }

        return true;
    }

    private void writeErrorResponse(HttpServletResponse response, int code, String msg) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(code);

        Result<Object> result = new Result<>();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(null);

        // 用 Jackson 写 JSON
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(result);

        response.getWriter().write(json);
    }
}
